/*"""
@Version: V1.0
@Author: willson
@License: Apache Licence
@Contact: willson.wu@goertek.com
@Site: goertek.com
@Software: GoLand
@File: main.go
@Time: 18-12-6 下午3:39
*/

package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

// 声明Redis链接对象，全局变量
var RedisClient *redis.Client

// 初始化redis客户端，即初始化链接对象
func init() {
	client := redis.NewClient(&redis.Options{
		Addr:     "redis:6379",
		DB:       0,
		PoolSize: 5, //redis 连接池数量
	})
	_, err := client.Ping().Result()
	if err != nil {
		log.Fatal("Redis connection is error:", err)
	}
	RedisClient = client
}

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	val, _ := RedisClient.Incr("hits").Result()
	_, _ = fmt.Fprintf(w, "<h1>Hello World! 该页面已经被访问了%d次,使用的是Go链接的Redis数据库!</h1>", val)
}

func Set(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_, err := RedisClient.Set(ps.ByName("name"), ps.ByName("name"), 0).Result()
	if err != nil {
		_, _ = fmt.Fprintf(w, "set, %s err!\n", ps.ByName("name"))
		return
	}
	_, _ = fmt.Fprintf(w, "set, %s O98K!\n", ps.ByName("name"))
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/set/:name", Set)

	log.Fatal(http.ListenAndServe(":8080", router))
}
